package http

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"mall-portalv2/global"
	"mall-portalv2/internal/server/ctx"
	"mall-portalv2/library/common"
	"net/http"
)

func SsoJiaChaoUserInfo(c *gin.Context) {
	app := ctx.Gin{C: c}

	type Data struct {
		Icon     string `json:"icon"`     // 头像
		Nickname string `json:"nickname"` // 昵称

		Unpaid     int64 `json:"unpaid"`     // 待付款数量
		Unreceived int64 `json:"unreceived"` // 待收货数量
		Unshipped  int64 `json:"unshipped"`  // 待发货数量
		AfterSales int64 `json:"afterSales"` // 售后数量
	}

	responseData := Data{}

	uidStr, isUid := c.Get("uid")
	if !isUid {
		global.Log.Error("uid不存在")
		app.Response(http.StatusInternalServerError, ctx.StatusInternalServerError, nil)
		return
	}
	UID := common.Str2Int64(fmt.Sprintf("%d", uidStr))

	global.Log.Info("命中路由", zap.Any("uid", UID), zap.Any("uidStr", fmt.Sprintf("%d", uidStr)))

	result, err := svc.QueryUmsMemberWhereID(c, UID)
	if err != nil {
		global.Log.Error("查询用户出了问题 ", zap.Error(err))
		app.Response(http.StatusInternalServerError, ctx.StatusInternalServerError, nil)
		return
	}

	responseData.Nickname = result.Nickname
	responseData.Icon = result.Icon

	// 订单详情
	OrdListResult, err := svc.QueryOmsOrderListAllAndNoMemberCom(c, UID)
	if err != nil {
		app.Response(http.StatusInternalServerError, ctx.StatusInternalServerError, err)
		return
	}

	for _, order := range OrdListResult {
		if order.DeleteStatus == 0 {
			switch order.Status {
			case 0:
				// 待付款
				responseData.Unpaid += 1
			case 1:
				// 待发货
				responseData.Unreceived += 1
			case 2:
				// 已发货
				responseData.Unshipped += 1
			}
		}
	}

	// 售后订单
	returnResult, err := svc.QueryOmsOrderReturnApplyCount(c, UID)
	if err != nil {
		global.Log.Error("查询用户售后单出了问题 ", zap.Error(err))
		app.Response(http.StatusInternalServerError, ctx.StatusInternalServerError, nil)
		return
	}

	responseData.AfterSales = returnResult

	app.Response(http.StatusOK, ctx.OK, responseData)
}
